package com.gr.gojcodesandbox.controller;

import com.gr.gojcodesandbox.codesandbox.cpp.CppNativeCodeSandBox;
import com.gr.gojcodesandbox.codesandbox.java.JavaNativeCodeSandBox;
import com.gr.gojcodesandbox.codesandbox.python.PythonNativeCodeSandBox;
import com.gr.gojcodesandbox.constants.CodeLanguage;
import com.gr.gojcodesandbox.model.ExecuteCodeRequest;
import com.gr.gojcodesandbox.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class MainController {

    // 定义鉴权请求头和密钥
    public static final String AUTH_REQUEST_HEADER = "auth";

    public static final String AUTH_REQUEST_SECRET = "secretKey";

    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    @Resource
    private CppNativeCodeSandBox cppNativeCodeSandBox;

    @Resource
    private PythonNativeCodeSandBox pythonNativeCodeSandBox;

    @GetMapping("/health")
    public String healthCheck() {
        return "ok";
    }

    /**
     * 执行代码
     *
     * @param executeCodeRequest
     * @return
     */
    @PostMapping("/executeCode")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request,
                                           HttpServletResponse response) {
        // 基本认证
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) {
            throw new RuntimeException("请求参数为空");
        }
        String language = executeCodeRequest.getLanguage();
        if (CodeLanguage.JAVA.equals(language)) {
            return javaNativeCodeSandBox.executeCode(executeCodeRequest);
        } else if (CodeLanguage.CPP.equals(language)) {
            return cppNativeCodeSandBox.executeCode(executeCodeRequest);
        } else if (CodeLanguage.PYTHON.equals(language)) {
            return pythonNativeCodeSandBox.executeCode(executeCodeRequest);
        } else {
            response.setStatus(404);
            return null;
        }
    }
}
